package edu.sdjzu.exam.service.course;

import edu.sdjzu.exam.domain.course.Course;
import edu.sdjzu.exam.domain.course.TeacherCourse;
import edu.sdjzu.exam.domain.auth.User;
import edu.sdjzu.exam.mapper.CourseMapper;
import edu.sdjzu.exam.mapper.TeacherCourseMapper;
import edu.sdjzu.exam.mapper.UserMapper;
import edu.sdjzu.exam.common.CommonResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CourseManagementService {
    
    private final CourseMapper courseMapper;
    private final TeacherCourseMapper teacherCourseMapper;
    private final UserMapper userMapper;

    @Transactional
    public  void deleteCourse(Integer courseId) {
        courseMapper.deleteCourse(courseId);
    }

    /**
     * 创建课程（超级管理员）
     */
    @Transactional
    public CommonResponse<Course> createCourse(String courseName, String courseCode, 
                                             String description, String subject, Long adminId) {
        try {
            Course course = new Course();
            course.setCourseName(courseName);
            course.setCourseCode(courseCode);
            course.setDescription(description);
            course.setSubject(subject);
            course.setCreatedBy(adminId);
            course.setStatus("active");
            
            courseMapper.insert(course);
            return CommonResponse.success("课程创建成功", course);
        } catch (Exception e) {
            return CommonResponse.fail(500, "创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 分配老师到课程（超级管理员）
     */
    @Transactional
    public CommonResponse<String> assignTeacherToCourse(Long teacherId, Long courseId, 
                                                       String permissionType, Long adminId) {
        try {
            // 验证老师存在且是老师角色
            User teacher = userMapper.findById(teacherId);
            if (teacher == null) {
                return CommonResponse.fail(404, "老师不存在");
            }
            
            // 验证课程存在
            Course course = courseMapper.findById(courseId);
            if (course == null) {
                return CommonResponse.fail(404, "课程不存在");
            }
            
            // 检查是否已经分配
            String existingPermission = teacherCourseMapper.getTeacherPermission(teacherId, courseId);
            if (existingPermission != null) {
                // 更新权限
                teacherCourseMapper.updatePermission(teacherId, courseId, permissionType);
                return CommonResponse.success("权限更新成功", null);
            } else {
                // 新增分配
                TeacherCourse teacherCourse = new TeacherCourse();
                teacherCourse.setTeacherId(teacherId);
                teacherCourse.setCourseId(courseId);
                teacherCourse.setPermissionType(permissionType);
                teacherCourse.setAssignedBy(adminId);
                teacherCourseMapper.insert(teacherCourse);
                return CommonResponse.success("分配成功", null);
            }
        } catch (Exception e) {
            return CommonResponse.fail(500, "分配失败：" + e.getMessage());
        }
    }
    
    /**
     * 移除老师的课程权限（超级管理员）
     */
    @Transactional
    public CommonResponse<String> removeTeacherFromCourse(Long teacherId, Long courseId) {
        try {
            int deleted = teacherCourseMapper.delete(teacherId, courseId);
            if (deleted > 0) {
                return CommonResponse.success("移除成功", null);
            } else {
                return CommonResponse.fail(404, "未找到相关权限记录");
            }
        } catch (Exception e) {
            return CommonResponse.fail(500, "移除失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查老师是否有课程权限
     */
    public boolean hasPermission(Long teacherId, Long courseId, String requiredPermission) {
        String permission = teacherCourseMapper.getTeacherPermission(teacherId, courseId);
        if (permission == null) {
            return false;
        }
        
        // 权限级别：admin > write > read
        switch (requiredPermission) {
            case "read":
                return true; // 有任何权限都可以读
            case "write":
                return "write".equals(permission) || "admin".equals(permission);
            case "admin":
                return "admin".equals(permission);
            default:
                return false;
        }
    }
    
    /**
     * 获取老师有权限的课程列表
     */
    public List<Course> getTeacherCourses(Long teacherId) {
        return courseMapper.findCoursesByTeacher(teacherId);
    }
    
    /**
     * 获取课程的授权老师列表
     */
    public List<TeacherCourse> getCourseTeachers(Long courseId) {
        return teacherCourseMapper.findTeachersByCourse(courseId);
    }
    
    /**
     * 获取所有课程列表
     */
    public List<Course> getAllCourses() {
        return courseMapper.findAllActiveCourses();
    }

    public void updateCourse(Course course) {
        courseMapper.update(course);
    }

    public List<Course> selectCourse() {
        return courseMapper.selectCourse();
    }
}